//
//  LeUtils.cpp
//  Leste
//
//  Created by 王乐 on 2022/1/26.
//

#include "LeUtils.h"

#include <glad/glad.h>
#include "stb_image.h"
#include <iostream>

// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int LeTextureLoader::loadTexture(const char *path)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);

    stbi_set_flip_vertically_on_load(true);
    int width, height, nrComponents;
    unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;
        else
            format = GL_RGBA;
            
        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}

#include <cstdlib> // Header file needed to use srand and rand
#include <ctime> // Header file needed to use time
#include <math.h>

unsigned LeMath::LeSeed;

LeMath::LeMath()
{

}

LeMath::~LeMath()
{

}

int LeMath::getRandomI(int min, int max)
{
    // Now generate and print three random numbers
    return (rand()%(max - min +1)) + min;
}

float LeMath::getRandomF(float min, float max)
{
    int randi = getRandomI(min * 100, max * 100);
    return (float)randi / 100.f;
}

float LeMath::lerpFloat(float x0, float x1, float ratio)
{
    return x0 + (x1 - x0) * ratio;
}

glm::vec3 LeMath::lerpVec3(glm::vec3 v0, glm::vec3 v1, float ratio)
{
    return glm::vec3(lerpFloat(v0.x, v1.x, ratio),
                     lerpFloat(v0.y, v1.y, ratio),
                     lerpFloat(v0.z, v1.z, ratio));
}

float LeMath::absFloat(float x)
{
    return std::abs(x);
}

LeSeed::LeSeed()
{
    unsigned seed;  // Random generator seed
    // Use the time function to get a "seed” value for srand
    seed = time(0);
    srand(seed);
}
